const time1El = document.querySelector(".time1");
const time2El = document.querySelector(".time2");
const time3El = document.querySelector(".time3");
const weekEl = document.querySelector(".week");
const dateEl = document.querySelector(".date");
const upEl = document.querySelector(".up");
const downEl = document.querySelector(".down");

// 即时时间
moment.locale("zh-cn");
function time() {
  time1El.innerHTML = moment().format("LTS");
}

time();
setInterval(time, 1000);

// 即时日期
const dayCn = window.calendar.solar2lunar(
  moment().year(),
  moment().month() + 1,
  moment().date()
);
console.log("🚀 ~ dayCn:", dayCn);
time2El.innerHTML =
  moment().format("LL") +
  " " +
  dayCn.IMonthCn +
  " " +
  dayCn.IDayCn +
  " " +
  dayCn.Term
    ? dayCn.Term
    : " ";

// 星期
const weekDay = moment.weekdaysMin(true);
weekDay.forEach((item) => (weekEl.innerHTML += `<span>${item}</span>`));

// 获取某月的天数
function getEndDay(moment) {
  return moment.daysInMonth();
}

// 获取某月第一天的星期
function getFirstWeek(moment) {
  return moment.startOf("month").weekday();
}

const today = moment();
setDate(today);
function setDate(m) {
  // 有修改的操作一定要克隆
  let lastEndDay = getEndDay(m.clone().subtract(1, "month"));
  const curEndDay = getEndDay(m);
  const week = getFirstWeek(m.clone());

  let str = "";
  let nextMonthStart = 0;

  for (let i = 0; i < 42; i++) {
    if (i < week) {
      str =
        `<li class="color"><span>${lastEndDay}</span><span>${getDayCn(
          m.year(),
          m.month(),
          lastEndDay
        )}</span></li>` + str;
      // 上个月
      lastEndDay--;
    } else if (i >= week + curEndDay) {
      // 下个月
      nextMonthStart++;
      str += `<li class="color"><span>${nextMonthStart}</span><span>${getDayCn(
        m.year(),
        m.month() + 2,
        nextMonthStart
      )}</span></li>`;
    } else {
      // 当前月
      let cls = m.date() === i - week + 1 ? "active" : "";

      if (m.year() !== moment().year() || m.month() !== moment().month()) {
        cls = "";
      }

      str += `<li class="${cls}"><span>${i - week + 1}</span><span>${getDayCn(
        m.year(),
        m.month(),
        i - week + 1
      )}</span></li>`;
    }
  }

  time3El.innerHTML = m.format("YYYY年MMM");
  dateEl.innerHTML = str;
}

upEl.onclick = function () {
  setDate(today.subtract(1, "month"));
};

downEl.onclick = function () {
  setDate(today.add(1, "month"));
};

// 获取农历
function getDayCn(year, month, date) {
  let dayCn = window.calendar.solar2lunar(year, month, date);
  let result = "";

  if (dayCn.IDayCn === "初一") {
    result = dayCn.IMonthCn;
  } else if (dayCn.Term) {
    result = dayCn.Term;
  } else if (dayCn.festival) {
    result = dayCn.festival;
  } else if (dayCn.lunarFestival) {
    result = dayCn.lunarFestival;
  } else {
    result = dayCn.IDayCn;
  }

  return result;
}
